import { InjectionKey } from 'vue'
import { createStore, Store, useStore as baseUseStore } from 'vuex'
import { IUserInfo } from '@/api/types/common'
import { setItem, getItem } from '@/utils/storage'
import { USER } from '@/utils/constants'

// 方式1.定义接口，指定state类型
// export interface State {
//   count:number,
//   isCollapse:boolean
// }

// 方式2. 提取state，定义state 类型为对象类型，这样就不用写两遍state了
const state = {
  count: 0,
  isCollapse: false,
  // 防止引用时 store.state.user 为null .xxx报错
  // user: JSON.parse(window.localStorage.getItem('user') || 'null') as IUserInfo | null
  // user: getItem<IUserInfo>('user')
  // 对 字符串 user 使用静态常量
  user: getItem<{token:string} & IUserInfo>(USER)
}
export type State = typeof state

// 定义 injection key
export const key: InjectionKey<Store<State>> = Symbol('store')

export const store = createStore<State>({
  // state () {
  //   return {
  //     count: 0,
  //     isCollapse: false
  //   }
  // },
  state,
  mutations: {
    increment (state) {
      state.count++
    },
    setIsCollapse (state, payload) {
      state.isCollapse = payload
    },
    setUser (state, payload) {
      state.user = payload
      // window.localStorage.setItem('user', JSON.stringify(state.user))
      // setItem('user', state.user)
      setItem(USER, state.user)
    }
  }
})

export function useStore () {
  // 把密钥key传给 useStore，已被改名为baseUseStore，封装了下
  return baseUseStore(key)
}
